﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Text;

namespace CoreHelper
{
    /// <summary>
    /// Http访问帮助类
    /// </summary>
    public class HttpRequest
    {

        private static ILogger<HttpRequest> _logger;

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public HttpRequest(ILogger<HttpRequest> logger)
        {
            _logger = logger;
        }
        #endregion        

        #region 解决https调用出现【基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系】错误
        /// <summary>
        /// 解决https调用出现【基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系】错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="certificate"></param>
        /// <param name="chain"></param>
        /// <param name="errors"></param>
        /// <returns></returns>
        private static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
        #endregion

        #region http post
        /// <summary>
        /// http post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="enc"></param>
        /// <param name="contentType"></param>
        /// <param name="proxyHost">代理</param>
        /// <param name="dicRequestHeaders">请求头,Dictionary</param>
        /// <returns></returns>
        public static string HttpPost(string url, string data, Encoding enc, string contentType = "application/x-www-form-urlencoded", string proxyHost = "", Dictionary<string, string> dicRequestHeaders = null)
        {
            string str = "";
            try
            {

                HttpWebRequest myHttpWebRequest;// = (HttpWebRequest)WebRequest.Create(url);

                //如果是发送HTTPS请求  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //网上一般都让加上这一行，如果不行换下面一行
                    //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    myHttpWebRequest = WebRequest.Create(url) as HttpWebRequest;
                    myHttpWebRequest.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    myHttpWebRequest = WebRequest.Create(url) as HttpWebRequest;
                }


                if (!string.IsNullOrEmpty(proxyHost))
                {
                    System.Net.WebProxy proxy = new WebProxy(proxyHost);
                    myHttpWebRequest.Proxy = proxy;
                }
                else
                {
                    myHttpWebRequest.Proxy = WebRequest.GetSystemWebProxy();
                }
                myHttpWebRequest.Method = "POST";
                if (dicRequestHeaders != null)
                {
                    foreach (var item in dicRequestHeaders)
                    {
                        myHttpWebRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                byte[] byte1 = enc.GetBytes(data);
                //myHttpWebRequest.Timeout=10;

                myHttpWebRequest.ContentType = contentType;

                myHttpWebRequest.ContentLength = data.Length;
                Stream newStream = myHttpWebRequest.GetRequestStream();
                newStream.Write(byte1, 0, byte1.Length);

                // Close the Stream object.
                newStream.Close();
                HttpWebResponse response = myHttpWebRequest.GetResponse() as HttpWebResponse;
                //Encoding enc = Encoding.GetEncoding(encode);
                // now we want to get the page contents of the target body
                using (StreamReader requestReader = new StreamReader(response.GetResponseStream(), enc))
                {
                    str = requestReader.ReadToEnd();
                }
                response.Close();
            }
            catch (System.Threading.ThreadAbortException e)
            {
                str = "error";
                //str = string.Format("{0},{1}", e.Message.ToString(), e.InnerException.ToString());

                _logger.LogInformation($"Message:{e.Message},InnerException:{e.InnerException}");
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    str = "error";
                    //str = string.Format("{0},{1}", e.Message.ToString(), e.InnerException.ToString());

                    _logger.LogInformation($"Message:{e.Message},InnerException:{e.InnerException}");
                }
            }
            catch (Exception e)
            {
                str = "error";
                //str = string.Format("{0},{1}", e.Message.ToString(), e.InnerException.ToString());

                _logger.LogInformation($"Message:{e.Message},InnerException:{e.InnerException}");
            }
            return str;
        }
        #endregion

        #region HttpGet
        /// <summary>
        /// HttpGet
        /// </summary>
        /// <param name="url"></param>
        /// <param name="proxyHost">代理地址</param>
        /// <param name="enc"></param>
        /// <returns></returns>
        public static string HttpGet(string url, string proxyHost, Encoding enc)
        {
            string strResult;

            HttpWebRequest myReq;// = (HttpWebRequest)HttpWebRequest.Create(url);
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                myReq = WebRequest.Create(url) as HttpWebRequest;
                myReq.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                myReq = WebRequest.Create(url) as HttpWebRequest;
            }
            myReq.UseDefaultCredentials = true;
            myReq.Timeout = 15000;
            if (!string.IsNullOrEmpty(proxyHost))
            {
                System.Net.WebProxy proxy = new WebProxy(proxyHost);
                myReq.Proxy = proxy;
            }
            else
            {
                myReq.Proxy = WebRequest.GetSystemWebProxy();
            }
            HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
            Stream myStream = HttpWResp.GetResponseStream();
            StreamReader sr = new StreamReader(myStream, enc);
            strResult = sr.ReadToEnd();
            sr.Close();
            myStream.Close();
            return strResult;
        }
        #endregion

        #region 指定编码GET
        /// <summary>
        /// 指定编码GET
        /// </summary>
        /// <param name="url"></param>
        /// <param name="enc"></param>
        /// <returns></returns>
        public static string HttpGet(string url, Encoding enc)
        {
            return HttpGet(url, null, enc);
        }
        #endregion
    }
}
